<?php

namespace api\modules\v1\controllers;

use api\modules\v1\models\LoginForm;
use common\models\User;
use yii\filters\auth\HttpBearerAuth;
use yii\helpers\ArrayHelper;
use yii\rest\Controller;
use Yii ;

/**
 * user Controller API
 *
 * @author zskj
 */
class UserController extends Controller
{
    public function behaviors()
    {
        return ArrayHelper::merge (parent::behaviors(), [
            'authenticator' => [
                'class' => HttpBearerAuth::class,
                'optional' => [
                    'login',
                    'signup-test'
                ],
            ]
        ] );
    }

    /**
     * 测试添加用户
     * @return mixed
     */
    public function actionSignupTest ()
    {
        $user = new User();
        $user->generateAuthKey();
        $user->setPassword('333');
        $user->username = '333';
        $user->email = '333@333.com';
        return $user->save(false);
    }

    /**
     * 登录
     * @return array
     * @throws \Exception
     */
    public function actionLogin()
    {
        $model = new LoginForm();
        $model->setAttributes(Yii::$app->request->post());
        if (($user = $model->login())) {
            return [
                'token' => $user->access_token
            ];
        } else {
            $errors = $model->errors;
            $firstError = current($errors);
            throw new \Exception( $firstError[0]);
        }
    }

    /**
     *
     */
    public function  actionProfile()
    {
        $user = $this->authenticate(Yii::$app->user, Yii::$app->request, Yii::$app->response);
        return [
            'id' => $user->id,
            'username' => $user->username,
            'email' => $user->email,
        ];
    }
}


